<script lang="ts">
    import { useFormItemContext } from "../FormItem/FormItem.svelte";
    import { useClassList } from "../utils/useClassList";
    import RateItem from "./RateItem.svelte";

    let { value = $bindable(0), ...props } = $props();
    const ctx = useFormItemContext();
    let current = $state(value);
    const allowHalf = props.allowHalf || false;

    const classList = $derived(
        useClassList(props, "cm-rate", {
            "cm-rate-disabled": props.disabled,
        })
    );

    if (!props.icon) {
        console.warn("need icon property");
    }

    const onMouseEnter = (val: number) => {
        current = val;
    };

    const onMouseEnterHalf = (val: number, e: any) => {
        if (!allowHalf) {
            return;
        }
        e.preventDefault();
        e.stopPropagation();
        current = val;
    };

    const onMouseLeave = () => {
        current = value;
    };

    const onClickStar = (val: number) => {
        value = val;
        props.onchange?.(val);
        ctx?.onFieldChange?.();
    };

    const onClickHalfStar = (val: number, e: any) => {
        e.preventDefault();
        e.stopPropagation();
        if (!allowHalf) {
            return;
        }
        value = val;
        props.onchange?.(val);
        ctx?.onFieldChange?.();
    };

    const count = props.count || 5;
    const stars: any[] = [];
    for (let i = 0; i < count; i++) {
        stars.push({ id: i, value: i });
    }
</script>

<!-- svelte-ignore a11y_no_static_element_interactions -->
<div style={props.style} class={classList} onmouseleave={onMouseLeave}>
    {#each stars as item, index (index)}
        <RateItem {index} {onMouseEnterHalf} {onClickHalfStar} {onMouseEnter} {onClickStar} icon={props.icon} {allowHalf} {current} />
    {/each}
    <span>{@render props.children?.()}</span>
</div>
